/**
 * 设置cookie天
 * @param {[type]} key   [键名]
 * @param {[type]} value [键值]
 * @param {[type]} days  [保存的时间（天）]
 */
const setCookieDay = (key: any, value: any, days: any) => {
  // 设置过期原则
  if (!value) {
    localStorage.removeItem(key)
  } else {
    var Days = days || 7; // 默认保留7天
    var exp = new Date();
    localStorage[key] = JSON.stringify({
      value,
      expire: exp.getTime() + Days * 24 * 60 * 60 * 1000
    })
  }
}
/**
 * 设置cookie
 * @param {[type]} key   [键名]
 * @param {[type]} value [键值]
 * @param {[type]} days  [保存的时间（毫秒）]
 */
const setCookie = (key: any, value: any, ts: any) => {
  if(!ts){
    localStorage[key] = JSON.stringify({
      value,
      expire: ts
    })
  }
  // 设置过期原则
  if (!value) {
    localStorage.removeItem(key)
  } else {
    var Ts = ts || 7 * 24 * 60 * 60 * 1000; // 默认保留7天
    var exp = new Date();
    localStorage[key] = JSON.stringify({
      value,
      expire: exp.getTime() + Ts
    })
  }
}
const clearCookie = (key: any) => {
  localStorage.removeItem(key)
}
const getCookie = (name: any) => {
  try {
    let o = JSON.parse(localStorage[name])
    if (!o || !o.expire || o.expire < Date.now()) {
      return null
    } else {
      return o.value
    }
  } catch (e) {
    // 兼容其他localstorage
    return localStorage[name]
  } finally {
  }
}

export {getCookie, setCookie, setCookieDay, clearCookie}
